package net.zhangbaolin.systemadmin.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import net.zhangbaolin.systemadmin.common.Jwt;
import net.zhangbaolin.systemadmin.common.RedisUtils;
import net.zhangbaolin.systemadmin.dao.PermissionDao;
import net.zhangbaolin.systemadmin.dao.UserDao;
import net.zhangbaolin.systemadmin.entity.Login;
import org.jose4j.jwt.MalformedClaimException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    Jwt jwt;
    @Resource
    UserDao userDao;

    @Resource
    RedisUtils redisUtils;

    @Resource
    PermissionDao permissionDao;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {


        if(Objects.equals(request.getRequestURI(), "/login")){
            filterChain.doFilter(request, response);
            return;
        }
        //获取token验证
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        Long id=null;
        //验证token
        try {
            id = Long.parseLong(jwt.verifyToken(token));
        } catch (MalformedClaimException e) {
            throw new RuntimeException(e);
        }

        //从redis获取用户信息
        Login login = JSON.parseObject((String) redisUtils.get("userid:" + id),new TypeReference<Login>() {});
        System.out.println((String) redisUtils.get("userid:" + id));
        System.out.println(login.toString());

        //获取角色字符 查询权限字符
        List<String> authorities = new ArrayList<>();
        for (GrantedAuthority authority : login.getAuthorities()) {
            authorities.add(authority.getAuthority());
        }

        List<String> list = permissionDao.selectPermsByRoleName(authorities);

        List<GrantedAuthority> gaList = list.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());

        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(login, null, gaList);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //放行
        filterChain.doFilter(request, response);
    }
}
